package com.androidx.xiecheng

import android.os.Bundle
import com.androidx.resource.BaseActivity
import com.androidx.resource.dddBug
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : BaseActivity() {
    lateinit var apiService: ApiService
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        apiService = Retrofit.Builder()
            .baseUrl("http://www.fangkeweiyou.com")
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)


        id_xiecheng_start.setOnClickListener {
//            startXiecheng()
//            apiService.getAppList()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe{
//                    dddBug(it.string())
//                }
            daojishi()
        }
    }

    var index = 0
    fun startXiecheng() {
        dddBug("开始启动协程:${Thread.currentThread().name}")
        GlobalScope.launch {
            val appList = apiService.getAppList()
            dddBug(appList.string())
        }
    }

    fun daojishi() {
        GlobalScope.launch {
            flow<Int> {
                (60 downTo 0).forEach {
                    //让协程进入等待状态
                    delay(1000)
                    emit(it)
                }
            }.flowOn(Dispatchers.Default)
                .onStart {
//// 倒计时开始 ，在这里可以让Button 禁止点击状态
                    dddBug("倒计时开始")
                }
                .onCompletion {
//// 倒计时结束 ，在这里可以让Button 恢复点击状态
                    dddBug("倒计时结束")
                }
                .collect {
// // 在这里 更新LiveData 的值来显示到UI
                    dddBug("倒计时:${it}")
                }
        }
    }
}